package com.ipt.frm.pw;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


/**
 * Servlet implementation class servletFile
 */

public class servletFile extends ServletMaestro {
	private static final long serialVersionUID = 8705702889664292048L;
	private static final String FILE_PATH = "C:/Desarrollo/workspace EE/";
	/**
     * @see HttpServlet#HttpServlet()
     */
    public servletFile() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
		try {
			
			response.setContentType("text/html");
		    PrintWriter out = response.getWriter();
			boolean isMultipart = ServletFileUpload.isMultipartContent(request);
			if(isMultipart){
				 DiskFileItemFactory factory = new DiskFileItemFactory();
				 ServletFileUpload upload = new ServletFileUpload(factory);
				   List fileItems = null;
				
					try {
						fileItems = upload.parseRequest(request);
					} catch (FileUploadException e) {
						System.out.println("Error fichero " + e);					
					}
								   
				   Iterator i = fileItems.iterator();
				   FileItem fi = (FileItem)i.next();				   				   
				   // filename on the client
				   String fileName = fi.getName();				   
				   // write the file
				   
				   //fi.write(new File(FILE_PATH,fileName));
				   //getRealPath lo guarda en C:\Desarrollo\apache-tomcat-6.0.37\webapps\PruebasWeb
				   fi.write(new File(getServletContext().getRealPath(""),fileName));				   

				   request.setAttribute("fichero", (getServletContext().getRealPath("") + "/" +fileName));
				   RequestDispatcher dispacher = this.getServletContext().getRequestDispatcher("/formulario.jsp");
		    		dispacher.forward(request, response);
			 }else
				 out.println("Fichero NO guardado");
		} catch (Exception e) {
			response.setContentType("text/html");
		    PrintWriter out = response.getWriter();
		    out.println("Fichero NO guardado");
		}			   
	}


}
